package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.Blog;
import com.yami.shop.bean.model.Comment;
import com.yami.shop.dao.BlogMapper;
import com.yami.shop.service.BlogService;
import com.yami.shop.service.CommentService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private CommentService commentService;
    @Override
    public void saveData(Blog blog) {
        // TODO 判断级别
        // 新增数据
        this.save(blog);
    }

    @Override
    public void addAndCancelPraiseCount(Long uid, Boolean isAdd) {
        if(isAdd){
            Blog byId = this.getById(uid);
            byId.setClickCount(byId.getClickCount()+1);
            this.updateById(byId);
        }else{
            Blog byId = this.getById(uid);
            if(byId.getClickCount()>0){
                byId.setClickCount(byId.getClickCount()-1);
                this.updateById(byId);
            }
        }
    }

    @Override
    public void addAndCancelCommentCount(Long uid, Boolean isAdd) {
        if(isAdd){
            Blog byId = this.getById(uid);
            byId.setCommentCount(byId.getCommentCount()+1);
            this.updateById(byId);
        }else{
            Blog byId = this.getById(uid);
            if(byId.getCommentCount()>0){
                byId.setCommentCount(byId.getCommentCount()-1);
                this.updateById(byId);
            }
        }
    }

    /**
     * 逻辑删除该用户评论或点赞别人的博客的数据
     *
     * @param userId
     */
    @Override
    public void deleteCommentListByUser(String userId) {
        //删除的点赞评论
        List<Long> delList = new ArrayList<>();
        //处理博客的点赞的评论
        List<Long> delBlogOneList = new ArrayList<>();
        //处理博客的评论的评论
        List<Long> delBlogTwoList = new ArrayList<>();
        Set<Long> delBlogList = new HashSet<>();

        // 1、先查询该用户自己的博客和圈子
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(Blog::getUserUid,userId);
        List<Blog> listBlog = blogMapper.selectList(blogLambdaQueryWrapper);

        // 2、查询出该用户评论或点赞别人的博客的数据
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getStatus, 1);
        commentLambdaQueryWrapper.eq(Comment::getUserUid, userId);
        if (ObjectUtils.isNotEmpty(listBlog)) {
            List<Long> blogIds = listBlog.stream().map(Blog::getUid).collect(Collectors.toList());
            commentLambdaQueryWrapper.notIn(Comment::getBlogUid, blogIds);
        }
        List<Comment> toCommentList = commentService.list(commentLambdaQueryWrapper);

        if (ObjectUtils.isNotEmpty(listBlog)) {
            List<Comment> update = new ArrayList();
            // 3、更新数据全部为删除状态
            listBlog.forEach(a -> {
                Comment comment = new Comment();
                comment.setUid(a.getUid());
                comment.setStatus(0);
                comment.setUpdateTime(new Date());
                update.add(comment);
            });
            commentService.updateBatchById(update);

            // 统计一级评论和点赞
            Map<Long, List<Comment>> upvote = toCommentList.stream().filter(s -> s.getType() == 1 && s.getToUid() == null).collect(Collectors.groupingBy(a -> a.getBlogUid()));
            Map<Long, List<Comment>> remark = toCommentList.stream().filter(s -> s.getType() == 0 && s.getToUid() == null).collect(Collectors.groupingBy(a -> a.getBlogUid()));

            Set<Long> blogIds = new HashSet<>();
            for (Map.Entry<Long, List<Comment>> entry : upvote.entrySet()) {
                blogIds.add(entry.getKey());
            }
            for (Map.Entry<Long, List<Comment>> entry : remark.entrySet()) {
                blogIds.add(entry.getKey());
            }

            // 4、需要更新点赞或者评论数的博客或圈子
            LambdaQueryWrapper<Blog> blogWrapper = new LambdaQueryWrapper<>();
            blogWrapper.in(Blog::getUid, blogIds);
            List<Blog> blogList = blogMapper.selectList(blogWrapper);

            List<Blog> updateBlog = new ArrayList<>();
            blogList.forEach(a -> {
                Blog blog = new Blog();
                blog.setUid(a.getUid());
                List<Comment> upvoteList = upvote.get(a.getUid());
                if (ObjectUtils.isNotEmpty(upvoteList)) {
                    int clickCount = a.getClickCount() - upvoteList.size() > 0 ? a.getClickCount() - upvoteList.size() : 0;
                    blog.setClickCount(clickCount);
                }
                List<Comment> remarkList = remark.get(a.getUid());
                if (ObjectUtils.isNotEmpty(remarkList)) {
                    int commentCount = a.getCommentCount() - remarkList.size() > 0 ? a.getCommentCount() - remarkList.size() : 0;
                    blog.setCommentCount(commentCount);
                }
                updateBlog.add(blog);
            });
            this.updateBatchById(updateBlog);
        }
    }
    @Override
    public void deleteBlogListByUser(String userId) {
        //查询是否有博客和圈子
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(Blog::getUserUid,userId);
        List<Blog> listBlog = blogMapper.selectList(blogLambdaQueryWrapper);
        // 物理删除 该用户创建的博客圈子，以及博客圈子下的评论和点赞
        if(listBlog.size()>0){
            List<Long> ids = new ArrayList<>();
            listBlog.forEach(item -> {
                ids.add(item.getUid());
            });
            if(ids.size()>0){
                //获取文章的点赞和评论及子点赞和评论
                LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
                wrapper.in(Comment::getBlogUid,ids);
                List<Comment> listAll = commentService.list(wrapper);
                commentService.removeBatchByIds(listAll);//删除所有评论和点赞
            }
            blogMapper.deleteBatchIds(listBlog);//删除博客和圈子
        }
        // 逻辑删除该用户评论或点赞别人的博客的数据
        deleteCommentListByUser(userId);
    }
}
